export function ajaxFileDownload(data, filename) {
  const a = document.createElement('a')
  var bstr = atob(data)
  var n = bstr.length
  var u8arr = new Uint8Array(n)
  while (n--) { u8arr[n] = bstr.charCodeAt(n) }
  var blob = new Blob([u8arr], {
    type: 'application/octet-stream,charset\x3dUTF-8'
  })
  var url = window.URL.createObjectURL(blob)
  a.href = url
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(url)
}
export async function ajaxFileDownload2(data, filename, directDownload) {
  console.log('window.showOpenFilePicker:::', window.showOpenFilePicker)
  if (!directDownload && typeof window.showOpenFilePicker === 'function') {
    const blob = new Blob([data])
    try {
      const handle = await window.showSaveFilePicker({
        suggestedName: filename
      })
      const writable = await handle.createWritable()
      await writable.write(blob)
      await writable.close()
      return handle
    } catch (e) {
      console.error(e)
      if (e.toString().indexOf('The user aborted a request') === -1) { exportFile(data, filename) }
    }
  } else { exportFile(data, filename) }
}
export function exportFile2(base64Str, filename) {
  const blob = base64toBlob(base64Str)
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  link.setAttribute('download', filename)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  window.URL.revokeObjectURL(url)
}
export function exportFile(data, filename) {
  if (typeof window.navigator.msSaveBlob !== 'undefined') {
    window.navigator.msSaveBlob(new Blob([data]), filename)
  } else {
    const blob = new Blob([data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', filename)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
  }
}

/**
 * 封装base64Str blob对象
 * */
function base64toBlob(base64Str) {
  const bstr = atob(base64Str)
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr])
}
